package com.live.dengdengtv.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.live.dengdengtv.BaseActivity;
import com.live.dengdengtv.R;
import com.live.dengdengtv.bean.AppInfo;
import com.live.dengdengtv.bean.SimpleInfoData;
import com.live.dengdengtv.bean.gson.PlayAdressByID_DB;
import com.live.dengdengtv.bean.gson.RecordPlayAdress_DB;
import com.live.dengdengtv.net.DianboNetTask;
import com.live.dengdengtv.net.NetTaskList;
import com.live.dengdengtv.utils.DateUtils;
import com.live.dengdengtv.view.DialogWaiting;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import okhttp3.Call;

public class DianboActivity extends BaseActivity implements View.OnClickListener, ITXLivePlayListener {

    private static final String TAG = "DianboActivity";



    private TXLivePlayer mLivePlayer;
    private TXCloudVideoView mPlayerView;



    private int              mCurrentRenderMode = TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION;
    private int              mCurrentRenderRotation = TXLiveConstants.RENDER_ROTATION_PORTRAIT;

    private TXLivePlayConfig mPlayConfig = new TXLivePlayConfig();

    private boolean          mVideoPlay = false;
    private int              mPlayType = TXLivePlayer.PLAY_TYPE_VOD_MP4;
    private boolean          mHWDecode   = false;
    private boolean          mVideoPause = false;
    private EditText input_message_et;
    private Button send_btn;

    private ListView listView;
    private ArrayList<ItemList> listViewData = new ArrayList<ItemList>();
    private MyAdapter adapter;

    private String fileId;
    private String vid;

    private DialogWaiting progressDialog;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dianbo);


        fileId = getIntent().getStringExtra("fileId");
        vid = getIntent().getStringExtra("vid");

        mPlayerView = (TXCloudVideoView) findViewById(R.id.video_view);
        mLivePlayer = new TXLivePlayer(DianboActivity.this);


        findViewById(R.id.play_iv).setOnClickListener(this);
        setCacheStrategy(CACHE_STRATEGY_AUTO);

        initInput();
        initListView();

        if(!TextUtils.isEmpty(fileId)){
            getVideoInfoById();
        }else {
            getRecordInfo();
        }
    }

    private void initListView() {
        listView = (ListView) findViewById(R.id.listView);
        adapter = new MyAdapter();
        listView.setAdapter(adapter);
    }

    private void initInput() {
        input_message_et = (EditText) findViewById(R.id.input_message_et);
        //软键盘事件监听
        input_message_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event)  {
                if (actionId== EditorInfo.IME_ACTION_SEND
                        ||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)) {
                    String text = input_message_et.getText().toString().trim();
                    if(!TextUtils.isEmpty(text)){
                        sendComment(text);
                        input_message_et.setText("");
                    }
                    return true;
                }
                return false;
            }
        });
        send_btn = (Button) findViewById(R.id.send_btn);
        send_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = input_message_et.getText().toString().trim();
                if(!TextUtils.isEmpty(text)){
                    sendComment(text);
                    input_message_et.setText("");
                }
            }
        });
    }

    private void getCommentList() {

        progressDialog = DialogWaiting.show(context);

        HashMap<String,String> params = new HashMap<String, String>();
        params.put("page", "1");
        params.put("page_count", "10");
        params.put("video_id", fileId);
        requestData(NetTaskList.get_comments, params,1);

//        Callback callback = new ProgressDialogCallBack(this,this);
//
//        OkHttpUtils.get().id(1).tag(this.getClass().getName()).url(NetTaskList.get_comments).params(params).build().execute(callback);
    }
    private void sendComment(String text) {

        HashMap<String,String> params = new HashMap<String, String>();
        params.put("content", text);
        params.put("video_id", fileId);
        params.putAll(AppInfo.getHeadInfo());
        requestData(NetTaskList.add_comment, params,2);
    }

    @Override
    public boolean onResponse(SimpleInfoData response, int id) {

        if(progressDialog!=null && progressDialog.isShowing()){
            progressDialog.dimiss();
        }

        if (response.result == 0) {
            if (id == 1) {
                if(response.data == null || !response.data.isJsonArray()) return false;
                JsonArray array = response.data.getAsJsonArray();
                for (int i=0; i<array.size() ;i++){
                    ItemList liveItem = new Gson().fromJson(array.get(i).getAsJsonObject(), ItemList.class);
                    listViewData.add(liveItem);
                }
                adapter.notifyDataSetChanged();
            }else if(id == 2){
                getCommentList();
            }
        }

        return false;
    }

    @Override
    public void onClick(View v) {
//        String vodUrl = "http://2527.vod.myqcloud.com/xxx.flv";
//        mLivePlayer.startPlay(vodUrl, TXLivePlayer.PLAY_TYPE_VOD_MP4);
//        getRecordInfo();
//        getVideoInfoById();

        if(!TextUtils.isEmpty(url)){
            int result = startPlayVideo(url);
            Log.e(TAG, "result = "+result) ;
        }
;
    }
    private void getVideoInfoById() {

        //vid   "200024932_3843ecdd7c4346498d9cb54b941e7890"
        DianboNetTask.getVideoInfoById(fileId, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, e.toString());
            }
            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, response);
                PlayAdressByID_DB categoryList = new Gson().fromJson(response, PlayAdressByID_DB.class);
                if(categoryList.code == 0){
                    url = categoryList.playSet.get(0).url;
                    Log.e(TAG, "result = "+categoryList.playSet.get(0).url);
                }else {
                    Log.e(TAG, response);
                }
                getCommentList();
            }
        });
    }

    private void getRecordInfo(){
        DianboNetTask.getRecordInfo(vid, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, response);
                RecordPlayAdress_DB recordList = new Gson().fromJson(response, RecordPlayAdress_DB.class);
                if(recordList.code == 0){
                    fileId = recordList.fileSet.get(0).fileId;
                    url = recordList.fileSet.get(0).playSet.get(0).url;

                    Log.e(TAG, "result = "+recordList.fileSet.get(0).playSet.get(0).url);
                    getCommentList();
                }else {
                    Log.e(TAG, response);
                }
            }
        });
    }

    private int startPlayVideo(String url){
        mLivePlayer.setPlayerView(mPlayerView);

        mLivePlayer.setPlayListener(DianboActivity.this);

        mLivePlayer.setRenderRotation(mCurrentRenderRotation);
        mLivePlayer.setRenderMode(mCurrentRenderMode);

        mLivePlayer.setConfig(mPlayConfig);

        return mLivePlayer.startPlay(url, TXLivePlayer.PLAY_TYPE_VOD_MP4);
    }

    public void onBackViewClick(View v) {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mLivePlayer != null) {
            mLivePlayer.resume();
        }


        if (mPlayerView != null) {
            mPlayerView.onResume();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mLivePlayer != null) {
            mLivePlayer.pause();
        }

        if (mPlayerView != null) {
            mPlayerView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        if (mLivePlayer != null) {
            mLivePlayer.stopPlay(true);
        }
        if (mPlayerView != null){
            mPlayerView.onDestroy();
        }
        super.onDestroy();
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listViewData.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (convertView != null) {
                holder = (ViewHolder)convertView.getTag();
            } else {
                convertView = View.inflate(context, R.layout.item_comment, null);

                holder = new ViewHolder();
                holder.name_tv = (TextView) convertView.findViewById(R.id.name_tv);
                holder.time_tv = (TextView) convertView.findViewById(R.id.time_tv);
                holder.comment_tv = (TextView) convertView.findViewById(R.id.comment_tv);
                holder.head_iv = (ImageView) convertView.findViewById(R.id.head_iv);

                convertView.setTag(holder);
            }

            String time = "";
            try {
                time = DateUtils.dateToString(new Date(listViewData.get(position).create_at*1000),"HH:mm");
            } catch (Exception e) {
                e.printStackTrace();
            }

            holder.name_tv.setText(listViewData.get(position).id);
            holder.time_tv.setText(time);
            holder.comment_tv.setText(listViewData.get(position).content);
            if(!TextUtils.isEmpty(listViewData.get(position).portrait)){
//                ImageLoader.getInstance().displayImage(listViewData.get(position).portrait, holder.head_iv);
                Glide.with(context).load(listViewData.get(position).portrait).into(holder.head_iv);
            }
            return convertView;
        }
    }

    private static class ViewHolder{
        TextView name_tv;
        TextView time_tv;
        TextView comment_tv;
        ImageView head_iv;
//        ImageView sex_iv;
//        ImageView level_iv;
    }
    private static class ItemList{
        String nickName;
        String content;
        int create_at;
        String id;
        String like_count;
        String portrait;
        String user_id;
        String video_id;
    }


    private static final int  CACHE_STRATEGY_FAST  = 1;  //极速
    private static final int  CACHE_STRATEGY_SMOOTH = 2;  //流畅
    private static final int  CACHE_STRATEGY_AUTO = 3;  //自动

    private static final int  CACHE_TIME_FAST = 1;
    private static final int  CACHE_TIME_SMOOTH = 5;

    private static final int  CACHE_TIME_AUTO_MIN = 5;
    private static final int  CACHE_TIME_AUTO_MAX = 10;
    private int              mCacheStrategy = 0;

    public void setCacheStrategy(int nCacheStrategy) {
        if (mCacheStrategy == nCacheStrategy)   return;
        mCacheStrategy = nCacheStrategy;

        switch (nCacheStrategy) {
            case CACHE_STRATEGY_FAST:
                mPlayConfig.setAutoAdjustCacheTime(true);
                mPlayConfig.setMaxAutoAdjustCacheTime(CACHE_TIME_FAST);
                mPlayConfig.setMinAutoAdjustCacheTime(CACHE_TIME_FAST);
                mLivePlayer.setConfig(mPlayConfig);
                break;

            case CACHE_STRATEGY_SMOOTH:
                mPlayConfig.setAutoAdjustCacheTime(false);
                mPlayConfig.setCacheTime(CACHE_TIME_SMOOTH);
                mLivePlayer.setConfig(mPlayConfig);
                break;

            case CACHE_STRATEGY_AUTO:
                mPlayConfig.setAutoAdjustCacheTime(true);
                mPlayConfig.setMaxAutoAdjustCacheTime(CACHE_TIME_AUTO_MAX);
                mPlayConfig.setMinAutoAdjustCacheTime(CACHE_TIME_AUTO_MIN);
                mLivePlayer.setConfig(mPlayConfig);
                break;

            default:
                break;
        }
    }
    @Override
    public void onPlayEvent(int i, Bundle bundle) {

    }

    @Override
    public void onNetStatus(Bundle bundle) {

    }


}
